package com.splic.product.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alicp.jetcache.anno.Cached;
import com.splic.common.utils.DateUtils;
import com.splic.common.utils.RandomCodeUtil;
import com.splic.common.utils.StringUtils;
import com.splic.product.domain.Device;
import com.splic.product.domain.DeviceProduct;
import com.splic.product.mapper.DeviceMapper;
import com.splic.product.mapper.DeviceProductMapper;
import com.splic.product.mapper.UserActiveMapper;
import com.splic.product.service.DeviceService;
import com.splic.product.service.UserService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 用户设备Service业务层处理
 * 
 * @author singe
 * @date 2022-01-04
 */
@Service
public class DeviceServiceImpl implements DeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private UserActiveMapper userActiveMapper;
    @Autowired
    private UserService userServiceImpl;
    @Autowired
    private DeviceProductMapper deviceProductMapper;

    /**
     * 查询用户设备
     * 
     * @param id 用户设备主键
     * @return 用户设备
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return deviceMapper.selectDeviceById(id);
    }

    /**
     * 查询用户设备列表
     * 
     * @param device 用户设备
     * @return 用户设备
     */
    @Override
    public List<Device> selectPageList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 查询用户设备列表
     *
     * @param device 用户设备
     * @return 用户设备
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        if (StringUtils.isEmpty(device.getStartCreateTime())) {
            device.setStartCreateTime(DateUtil.formatDate(DateUtil.offsetDay(new Date(), -7)));
        }
        if (StringUtils.isEmpty(device.getEndCreateTime())) {
            device.setEndCreateTime(DateUtil.formatDate(DateUtil.offsetDay(new Date(), 1)));
        } else {
            device.setEndCreateTime(DateUtil.formatDate(DateUtil.offsetDay(DateUtils.parseDate(device.getEndCreateTime()), 1)));
        }
        List<Device> deviceList = deviceMapper.selectDeviceList(device);
        if (deviceList != null && deviceList.size() > 0) {
            List<Map<String, Long>> mapList = deviceProductMapper.selectProductNumByDevice(deviceList);
            List<Map<String, Object>> maps = userActiveMapper.selectActiveByDevice(deviceList);
            Map<Long, Long> deviceProductMap = new HashMap<>();
            Map<Long, Map<String, Object>> deviceActiveMap = new HashMap<>();
            for (Map<String, Long> map : mapList) {
                deviceProductMap.put(map.get("id"), map.get("productNumber"));
            }
            for (Map<String, Object> map : maps) {
                deviceActiveMap.put((Long) map.get("deviceId"), map);
            }
            for (Device device1 : deviceList) {
                if (deviceProductMap.containsKey(device1.getId())) {
                    device1.setProductNum(deviceProductMap.get(device1.getId()).intValue());
                }
                if (deviceActiveMap.containsKey(device1.getId())) {
                    device1.setLastApp((String) deviceActiveMap.get(device1.getId()).get("productName"));
                    device1.setLastAppTime((LocalDateTime) deviceActiveMap.get(device1.getId()).get("createTime"));
                }
            }
        }
        return deviceList;
    }

    /**
     * 新增用户设备
     * 
     * @param device 用户设备
     * @return 结果
     */
    @Override
    public int insert(Device device)
    {
        device.setCreateTime(DateUtils.getNowDate());
        return deviceMapper.insert(device);
    }

    /**
     * 修改用户设备
     * 
     * @param device 用户设备
     * @return 结果
     */
    @Override
    public int update(Device device)
    {
        device.setUpdateTime(DateUtils.getNowDate());
        return deviceMapper.update(device);
    }


    /**
     * 删除用户设备信息
     * 
     * @param id 用户设备主键
     * @return 结果
     */
    @Override
    public int deleteById(Long id)
    {
        return deviceMapper.deleteById(id);
    }
    /**
     * 修改用户设备
     *
     * @param device 用户设备信息
     * @return 结果
     */
    @Override
    public synchronized int saveOrUpdate(Device device)
    {
        getDeviceIdentify(device);
        if(device.getId() != null){
            device.setUpdateTime(new Date());
            return deviceMapper.update(device);
        }else{
            device.setDeviceIdentify(getIdentify());
            device.setCreateTime(new Date());
            int result = deviceMapper.insert(device);
            if (result == 1) {
                try {
                    if (device.getProductId() != null) {
                        DeviceProduct deviceProduct = new DeviceProduct();
                        deviceProduct.setDeviceId(device.getId());
                        deviceProduct.setProductId(device.getProductId());
                        deviceProduct.setCreateTime(new Date());
                        deviceProductMapper.insert(deviceProduct);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return result;
            } else {
                return 0;
            }
        }
    }
    /**
     * 获取设备标识和设备id
     * @param device
     * @return
     */
    public Device getDeviceIdentify(Device device){
        Device deviceQuery = null;
        if (StringUtils.isNotEmpty(device.getDeviceIdentify())){
            deviceQuery = getByDeviceIdentify(device.getDeviceIdentify());
        }else {
            if (device.getId() == null && StringUtils.isNotEmpty(device.getAndroidId())) {
                deviceQuery = getByAndroidId(device.getAndroidId());
            }
            if (device.getId() == null && StringUtils.isNotEmpty(device.getMac())) {
                deviceQuery = getByMac(device.getMac());
            }
            if (device.getId() == null && StringUtils.isNotEmpty(device.getOaid())) {
                deviceQuery = getByOaid(device.getOaid());
            }
            if (device.getId() == null && StringUtils.isNotEmpty(device.getVaid())) {
                deviceQuery = getByVaid(device.getVaid());
            }
            if (device.getId() == null && StringUtils.isNotEmpty(device.getGaid())) {
                deviceQuery = getByGaid(device.getGaid());
            }
            if (device.getId() == null && StringUtils.isNotEmpty(device.getImei())) {
                deviceQuery = getByImei(device.getImei());
            }
        }
        if (deviceQuery == null) {
            return device;
        } else {
            device.setId(deviceQuery.getId());
            device.setDeviceIdentify(deviceQuery.getDeviceIdentify());
        }
        return deviceQuery;
    }

   private String getIdentify(){
        String deviceIdentify = RandomCodeUtil.identifyCode("DE");
        Device device = this.getByDeviceIdentify(deviceIdentify);
        if (device != null){
            return getIdentify();
        }
        return deviceIdentify;
    }


    @Override
    public Device selectDeviceByUserId(Long userId) {
        List<Device> deviceList = deviceMapper.selectDeviceByUserId(userId);
        if(CollectionUtils.isNotEmpty(deviceList)){
            return deviceList.get(0);
        }
        return null;
    }


    @Override
    public int updateDeviceIsBlackList(Long id) {
        return deviceMapper.updateDeviceIsBlackList(id);
    }

    @Override
    public List<Device> getByIds(Set<Long> deviceIdSet) {
        return deviceMapper.getByIds(deviceIdSet);
    }

    @Override
    public List<String> selectResolvingPowerList() {
        return deviceMapper.selectResolvingPowerList();
    }

    @Override
    public Device getByDeviceIdentify(String deviceIdentify) {
        return deviceMapper.getByDeviceIdentify(deviceIdentify);
    }

    @Override
    public Device getByAndroidId(String androidId) {
        return deviceMapper.getByAndroidId(androidId);
    }

    @Override
    public Device getByMac(String mac) {
        return deviceMapper.getByMac(mac);
    }

    @Override
    public Device getByOaid(String oaid) {
        return deviceMapper.getByOaid(oaid);
    }

    @Override
    public Device getByVaid(String vaid) {
        return deviceMapper.getByVaid(vaid);
    }

    @Override
    public Device getByGaid(String gaid) {
        return deviceMapper.getByGaid(gaid);
    }

    @Override
    public Device getByImei(String imei) {
        return deviceMapper.getByImei(imei);
    }
}
